##Replication code for "drivers of resemblance: explaining the conversion of pre-electoral coalitions
##into coalition cabinets"
library(QCA)
library(tidyverse)
library(ragg)
library(SetMethods)
library(showtext)

sec <- read.csv("dpr.csv", sep=";")


##Calibration Process----
sec1 <- sec %>%
        filter(type == "pre") %>%
        select(-type, -legislative_type, -inter_party_primaries,
               -low_chamber, -upp_chamber, -status, -country, -ce) %>%
        column_to_rownames(var = "cases")

sec2 <- sec1 %>%
        mutate(lwpol = calibrate(lwpol, type = "fuzzy", method = "direct", threshold = "e=3, c=2, i=1")) %>%
        mutate(hlpol = calibrate(hlpol, type = "fuzzy", method = "direct", threshold = "e=1.5, c=2.7, i=4")) %>%
        mutate(htemp = calibrate(htemp, type = "fuzzy", method = "direct", threshold = "e=85, c=70, i=55")) %>%
        mutate(lplp = calibrate(lplp, type = "fuzzy", method = "direct", threshold = "e=0.5, c=0.405, i=0.3")) %>%
        rename(LWPOL = lwpol,
               MAJ = maj, 
               HLPOL = hlpol,
               HTEMP = htemp,
               LPP = lplp,
               CR = cr)

TTsec <- truthTable(sec2, outcome = "CR",
                    complete = TRUE, incl.cut = 0.8,
                    sort.by = "incl, n+",
                    show.cases = TRUE)

ESA <- findRows("~MAJ*~HTEMP", obj = TTsec)

intermediate_result <- minimize(TTsec, include = "?", details = TRUE, dir.exp = "1,1,1,1,1", exclude = ESA)

##XY Plot for Sufficiency----
#standard version
sol <- "MAJ*LWPOL + MAJ*HLPOL*HTEMP + HLPOL*HTEMP*LPP + LWPOL*HLPOL*~HTEMP*~LPP"

##This produces a raw plot from the QCA package
XYplot(sol, "CR" , data = sec2, enhance = T, relation = "sufficiency", jitter = T, 
       clabels = rownames(sec2), xlab = "Solution Formula", ylab = "CR", 
       family = "regular",
       cex = 1)

#Fonts
##Please download the fonts below on https://fonts.google.com/specimen/Barlow+Semi+Condensed to reproduce the figure in its entirety.
font_add(family = "regular", "Barlow Semi Condensed-Regular.ttf")
font_add(family= "bold", "BarlowSemiCondensed-SemiBold.ttf")
showtext_auto()   

#Plot
##This produces Figure A.2 in the Supplementary Material
xyplot_suc <- sec2 %>% mutate(sol1 = pmin(MAJ, LWPOL),
                              sol2 = pmin(MAJ, HLPOL, HTEMP),
                              sol3 = pmin(HLPOL, HTEMP, LPP),
                              htemp = 1 - HTEMP,
                              lpp = 1 - LPP,
                              sol4 = pmin(LWPOL, HLPOL, htemp, lpp),
                              sol_all = pmax(sol1, sol2, sol3, sol4),
                              rownames = c("", "Macri", "Siles", "Paz Zamora", "Banzer", "Cardoso I","Cardoso II", "Lula I", "Lula II", "",
                                           "", "", "", "", "", "", "", "", "", "",
                                           "", "", "Balladares", "", "", "Martinelli", "Varela", "", "", "Caldera", ""),
                              interest = case_when(rownames == "Macri" ~ "Deviant Coverage" ,
                                                   rownames == "Caldera" ~ "Deviant Coverage",
                                                   rownames == "Balladares" ~ "Deviant Consistency in Kind",
                                                   rownames == "Lula II" ~ "Individually Irrelevant",
                                                   rownames == "Paz Zamora" ~ "Individually Irrelevant",
                                                   rownames == "Lula I" ~ "Individually Irrelevant",
                                                   rownames == "Varela" ~ "Individually Irrelevant",
                                                   rownames == "Banzer" ~ "Individually Irrelevant",
                                                   rownames == "Siles" ~ "Deviant Consistency in Degree",
                                                   rownames == "Martinelli" ~ "Deviant Consistency in Degree",
                                                   rownames == "Cardoso I" ~ "Deviant Consistency in Degree",
                                                   rownames == "Cardoso II" ~ "Deviant Consistency in Degree"
                              ),
                              interest = replace_na(interest, "Typical"),
                              interest = factor(interest, levels = c("Deviant Consistency in Kind", "Deviant Consistency in Degree", "Deviant Coverage",  "Individually Irrelevant", "Typical")),
                              rownames = c("", "Macri", "", "", "", "", "",
                                           "", "", "", "", "", "", "", "", "",
                                           "", "", "", "", "", "", "Balladares", "",
                                           "", "", "", "", "", "Caldera", "")) %>%
  ggplot(aes(sol_all, CR)) +
  geom_point(aes(colour = interest, fill = interest, shape = interest), size = 2, position = "jitter") +
  geom_text_repel(aes(label = rownames), size = 12, family = "regular") +
  geom_abline(intercept = 0, slope = 1) +
  geom_hline(yintercept = 0.5, linetype = 2) +
  geom_vline(xintercept = 0.5, linetype = 2) +
  coord_cartesian(expand=FALSE) +
  scale_color_manual(values = c("#E8080c","#808080", "#bb517d","#c0c0c0", "#90d5e8")) +
  scale_fill_manual(values = c("#E8080c","#808080", "#bb517d","#c0c0c0", "#90d5e8")) +
  scale_shape_manual(values = c(23, 19, 19, 19, 19))+
  scale_x_continuous(limits = c(-0.02, 1.02),
                     breaks = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)) +
  scale_y_continuous(limits = c(-0.02, 1.02),
                     breaks = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)) +
  xlab("Solution Formula") + ylab("CR") +
  labs(title = "Sufficiency Relation",
       subtitle = "Inclusion: 0.920 - PRI: 0.907 - Coverage: 0.807",
       shape = "Types of Cases",
       colour = "Types of Cases",
       fill = "Types of Cases") +
  guides(fill=guide_legend(ncol = 3) ,
         colour=guide_legend(ncol = 3),
         shape=guide_legend(ncol = 3)) +
  theme(
    #Title, Subtitle, Caption
    plot.title = element_text(family = "bold", hjust = 0.5, vjust = 0.5, size = 45, color = "black"),
    plot.title.position = "plot",
    plot.subtitle = element_text(family="regular", size = 40, hjust = 0.5, color = "black"),
    #Panel and Background
    panel.background = element_rect(color = "black", fill = "#ffffff"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    #panel.background = element_rect(fill = "white"),
    plot.background = element_rect(fill = "#ffffff", linetype = 'blank'),
    #Axes
    axis.title = element_text(size = 40, family = "bold", color = "black"),
    axis.text.y = element_text(size = 30, family = "regular", color = "black"),
    axis.text.x = element_text(size = 30, family = "regular", color = "black"),
    axis.ticks = element_line(color = "black"),
    axis.line = element_blank(),
    #Plus
    text = element_text(family = "regular", size = 35),
    legend.text = element_text(size=30, family="regular"),
    legend.position = "top",
    legend.key = element_blank(),
    legend.key.width = unit(0.2, "cm")) 

ggsave("xyplot_suf.png",
       plot=xyplot_suc,
       device = agg_png(width = 6.5, height = 6, units = "in", res = 300))
